package project.rbac.util;

import project.rbac.exception.FatalException;

import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 工具类-单例工厂
 *
 * @author 刘嘉薏
 * @since 2025/6/5 17:37
 */
public class SingletonFactory {
    private static final Map<Class<?>, Object> instanceMap = new ConcurrentHashMap<>();

    public static <T> T getInstance(Class<T> clazz) {
        if (clazz == null) {
            //throw new IllegalArgumentException("未知的类型");
            throw new FatalException();
        }
        if (!instanceMap.containsKey(clazz)) {
            try {
                Constructor<T> constructor = clazz.getDeclaredConstructor();
                constructor.setAccessible(true);
                T singleton = constructor.newInstance();
                instanceMap.put(clazz, singleton);
            } catch (Exception e) {
                //throw new IllegalArgumentException("创建单例失败：" + clazz.getSimpleName(), e);
                throw new FatalException(e);
            }
        }
        @SuppressWarnings("unchecked")
        T instance = (T) instanceMap.get(clazz);
        return instance;
//        Object obj = instanceMap.get(clazz);
//        if (clazz.isInstance(obj)){
//            return clazz.cast(obj);
//        }else {
//            throw new IllegalArgumentException("创建单例失败：" + clazz.getSimpleName());
//        }
    }
}
